﻿namespace TomatoBreak.Web
{
    using System;
    using System.Web.Mvc;

    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    using Newtonsoft.Json.Serialization;

    public class JsonNetResult : JsonResult
    {
        public JsonNetResult()
        {
            Settings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            Settings.Converters.Add(new IsoDateTimeConverter
                                        {
                                            DateTimeFormat  = "yyyy-MM-dd"
                                        });
        }

        public int HttpStatusCode { get; set; }

        public Formatting Formatting { get; set; }

        public JsonSerializerSettings Settings { get; private set; }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("Get must be explicitly specified.");
            }

            var response = context.HttpContext.Response;

            response.ContentType = string.IsNullOrWhiteSpace(ContentType) ?
                                   "application/json" :
                                   ContentType;

            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }

            if (Data == null)
            {
                return;
            }

            using (var writer = new JsonTextWriter(response.Output)
                                    {
                                        Formatting = Formatting
                                    })
            {
                JsonSerializer.Create(Settings).Serialize(writer, Data);
            }

            response.StatusCode = HttpStatusCode;
        }
    }
}